Debugging a script or function

Problem

You want to debug a script or function.

Solution

Insert this into your code at the place where you want to start debugging:

browser()

It will pause your code and you will be able to look at and change variables.

In the browser, typing these letters will do things:

c Continue
n (or Return) Next step
Q quit
Ctrl-C go to top level

When in the browser, you can see what variables are in the current scope.

objects()

To pause and start a browser for every line in your function:

debug(myfunction)
myfunction(x)

To start debugging when an error is thrown, run this before your function which throws an error:

options(error=recover)